#import "DDRequest.h"
@interface DDRequest()
@property (nonatomic, strong) NSMutableDictionary *para;
@property (nonatomic, strong) NSMutableData *data;
@property (nonatomic, strong) loginBlock login_block;
@end
@implementation DDRequest
- (NSMutableDictionary *)para
{
    if (!_para)
    {
        _para = [NSMutableDictionary dictionaryWithDictionary:[DDHelper help].localInfo];
    }
    return _para;
}
- (NSMutableData *)data
{
    if (!_data)
    {
        _data = [NSMutableData data];
    }
    return _data;
}
- (void)dd_YJ_registerRequst
{
    self.type = JTWRequestTypeYJ_Register;
    [self.para setValue:@"" forKey:@"account"];
    [self.para setValue:@"" forKey:@"pass"];
    [self dd_request];
}
- (void)dd_visitorRequest
{
    self.type = JTWRequestTypeVisitor;
    [self.para setValue:@"" forKey:@"account"];
    [self.para setValue:@"" forKey:@"pass"];
    [self dd_request];
}
- (void)dd_registerRequst:(NSDictionary *)dict
{
    self.type = JTWRequestTypeRegister;
    [self.para setValue:[dict valueForKey:@"name"] forKey:@"account"];
    [self.para setValue:[[dict valueForKey:@"password"] dd_md5] forKey:@"pass"];
    [self dd_request];
}
- (void)dd_loginRequest:(NSDictionary *)dict
{
    self.type = JTWRequestTypeLogin;
    [self.para setValue:[dict valueForKey:@"name"] forKey:@"account"];
    [self.para setValue:[[dict valueForKey:@"password"] dd_md5] forKey:@"pass"];
    [self dd_request];
}
- (void)dd_loginRequestWithBlock:(loginBlock)block
{
    self.type = JTWRequestTypeLogin;
    self.login_block = block;
    [self.para setValue:@"" forKey:@"account"];
    [self.para setValue:@"" forKey:@"pass"];
    [self dd_request];
    
}
- (void)dd_authenticateRequest:(NSDictionary *)dict;
{
    self.type = JTWRequestTypeAuthenticate;
    [self.para removeAllObjects];
    [self.para setDictionary:dict];
    [self.para setValue:[DDHelper help].accountID forKey:@"accountid"];
    [self.para setValue:[DDHelper help].appID forKey:@"appid"];
    [self dd_request];
}
- (void)dd_verifyCodeRequest:(NSDictionary *)dict
{
    self.type = JTWRequestTypeVerifyCode;
    [self.para removeAllObjects];
    [self.para setDictionary:dict];
    [self.para setValue:[DDHelper help].appID forKey:@"appid"];
    [self dd_request];
}
- (void)dd_resetPWDRequest:(NSDictionary *)dict
{
    self.type = JTWRequestTypeResetPWD;
    [self.para setValue:[DDHelper help].appID forKey:@"appid"];
    [self.para setValue:[dict valueForKey:@"account"] forKey:@"account"];
    [self.para setValue:[[dict valueForKey:@"pass"] dd_md5] forKey:@"pass"];
    [self.para setValue:[dict valueForKey:@"phone"] forKey:@"phone"];
    [self dd_request];
}
- (void)dd_alterPWDRequest:(NSDictionary *)dict
{
    [self.para removeAllObjects];
    self.type = JTWRequestTypeAlterPWD;
    [self.para setValue:[DDHelper help].appID forKey:@"appid"];
    [self.para setValue:[DDHelper help].accountID forKey:@"accountid"];
    [self.para setValue:[[dict valueForKey:@"oldpassword"] dd_md5] forKey:@"pass"];
    [self.para setValue:[[dict valueForKey:@"password"] dd_md5] forKey:@"password"];
    [self dd_request];
}
- (void)dd_bindRequest:(NSDictionary *)dict
{
    self.type = JTWRequestTypeBind;
    [self.para removeAllObjects];
    [self.para setDictionary:dict];
    [self.para setValue:[DDHelper help].appID forKey:@"appid"];
    [self.para setValue:[DDHelper help].accountID forKey:@"accountid"];
    [self dd_request];
}
- (void)dd_prepareZFRequest:(DDProduct *)product
{
    self.para = nil;
    self.type = JTWRequestTypePrepareZF;
    [self.para insertDict:[product dd_propertyDic]];
    [self.para setValue:[DDHelper help].accountID forKey:@"accountid"];
    [self.para setValue:[DDHelper help].gameAccountID forKey:@"gameaccountid"];
    [self dd_request];
}
- (void)dd_zfRequest:(DDProduct *)product
{
    self.para = nil;
    self.type = JTWRequestTypeZF;
    [self.para insertDict:[product dd_propertyDic]];
    [self.para setValue:[DDHelper help].accountID forKey:@"accountid"];
    [self.para setValue:[DDHelper help].gameAccountID forKey:@"gameaccountid"];
    [self dd_request];
}
- (void)dd_exchangeRequest:(NSDictionary *)dict
{
    self.para = nil;
    self.type = JTWRequestTypeExchange;
    [self.para insertDict:dict];
    [self.para setValue:[DDHelper help].accountID forKey:@"accountid"];
    [self dd_request];
}
- (void)yd_updateRoleInfo:(NSDictionary *)dict
{
    self.type = JTWRequestTypeUpdateRoleInfo;
    [self.para insertDict:dict];
    [self.para setValue:[DDHelper help].appID forKey:@"appid"];
    [self.para setValue:[DDHelper help].accountID forKey:@"accountid"];
    [self.para setValue:[DDHelper help].gameAccountID forKey:@"gameaccountid"];
    [self dd_request];
}
- (void)dd_request
{
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    NSString *paraString = [self.para json];
    [requestPara setValue:paraString forKey:@"transdata"];
    NSString *sign = [paraString dd_sign];
    [requestPara setValue:sign forKey:@"sign"];
    [requestPara setValue:@"RSA" forKey:@"signtype"];
    [CCHttp http].basicURLString = [DDHelper help].serviceHeader;
    [self.task cancel];
    self.data = nil;
    NSString *api = @"";
    if (self.type == JTWRequestTypeLogin)
        api = LOGIN_API;
    else if (self.type == JTWRequestTypeRegister || self.type == JTWRequestTypeQuickRegister || self.type == JTWRequestTypeYJ_Register || self.type == JTWRequestTypeVisitor)
        api = REGISTE_API;
    else if (self.type == JTWRequestTypeAuthenticate)
        api = AUTHENTICATE_API;
    else if (self.type == JTWRequestTypeVerifyCode)
        api = VERIFYCODE_API;
    else if (self.type == JTWRequestTypeResetPWD)
        api = RESETPASSWORD_API;
    else if (self.type == JTWRequestTypeAlterPWD)
        api = ALTERPASSWORD_API;
    else if (self.type == JTWRequestTypeBind)
        api = BIND_API;
    else if (self.type == JTWRequestTypePrepareZF)
        api = PREPARE_ZF_API;
    else if (self.type == JTWRequestTypeZF)
        api = ZF_API;
    else if (self.type == JTWRequestTypeExchange)
        api = EXCHANGE_API;
    else if (self.type == JTWRequestTypeUpdateRoleInfo)
        api = UPDATE_ROLEINFO_API;
    self.task = [CCHttp post:api para:requestPara success:^(id  _Nonnull response) {
        NSDictionary *dict = (NSDictionary *)response;
        if (dict)
        {
            NSString *sign = [dict valueForKey:@"sign"];
            NSString *transdata = [dict valueForKey:@"transdata"];
            BOOL isSuccess = [transdata dd_verifySign:sign];
            if (isSuccess)
            {
                NSDictionary *trans = [NSJSONSerialization JSONObjectWithData:[transdata dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
                if (self.delegate && [self.delegate respondsToSelector:@selector(dd_didRequestWithReceiveData:error:)])
                {
                    [self.delegate dd_didRequestWithReceiveData:trans error:nil];
                }
                else if (self.delegate == nil && self.login_block)
                {
                    self.login_block(trans);
                }
            }
            else
            {
                DeLog(@"验证失败");
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (self.delegate && [self.delegate respondsToSelector:@selector(dd_didRequestWithReceiveData:error:)])
                    {
                        [self.delegate dd_didRequestWithReceiveData:nil error:nil];
                    }
                    else if (self.delegate == nil && self.login_block)
                    {
                        self.login_block(nil);
                    }
                });
            }
        }
    } fail:^(NSError * _Nonnull error) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(dd_didRequestWithReceiveData:error:)])
        {
            [self.delegate dd_didRequestWithReceiveData:nil error:error];
        }
        else if (self.delegate == nil && self.login_block)
        {
            self.login_block(nil);
        }
    }];
    
}
#pragma mark - NSURLSessionDataDelegate method
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    completionHandler(NSURLSessionResponseAllow);
}
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}
-(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error
{
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error
{
    if (error)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.delegate && [self.delegate respondsToSelector:@selector(dd_didRequestWithReceiveData:error:)])
            {
                [self.delegate dd_didRequestWithReceiveData:nil error:error];
            }
            else if (self.delegate == nil && self.login_block)
            {
                self.login_block(nil);
            }
        });
        return;
    }
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingMutableLeaves error:nil];
    if (dict)
    {
        NSString *sign = [dict valueForKey:@"sign"];
        NSString *transdata = [dict valueForKey:@"transdata"];
        BOOL isSuccess = [transdata dd_verifySign:sign];
        if (isSuccess)
        {
            NSDictionary *trans = [NSJSONSerialization JSONObjectWithData:[transdata dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.delegate && [self.delegate respondsToSelector:@selector(dd_didRequestWithReceiveData:error:)])
                {
                    [self.delegate dd_didRequestWithReceiveData:trans error:nil];
                }
                else if (self.delegate == nil && self.login_block)
                {
                    self.login_block(trans);
                }
            });
        }
        else
        {
            DeLog(@"验证失败");
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.delegate && [self.delegate respondsToSelector:@selector(dd_didRequestWithReceiveData:error:)])
                {
                    [self.delegate dd_didRequestWithReceiveData:nil error:nil];
                }
                else if (self.delegate == nil && self.login_block)
                {
                    self.login_block(nil);
                }
            });
        }
    }
    else
    {
        NSLog(@"dict %@",dict);
        dispatch_async(dispatch_get_main_queue(), ^{
            [CCHud stopHud];
            [CCAlert showMessage:@"参数错误" hidden:nil];
        });
    }
    self.data = nil;
    [session finishTasksAndInvalidate];
}
- (void)dealloc
{
    [self.task cancel];
    self.task = nil;
}
@end
